package com.zlyx.easy.core.utils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

/**
 * @Auth 赵光
 * @Describle
 * @2019年6月21日 下午10:30:32
 */
public final class RestUtils {

	private static RestTemplate restTemplate;

	public static RestTemplate getRestTemplate() {
		if (restTemplate == null) {
			SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
			factory.setReadTimeout(180000);// 单位为ms
			factory.setConnectTimeout(5000);// 单位为ms
			restTemplate = new RestTemplate(factory);
			List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
			for (HttpMessageConverter<?> httpMessageConverter : list) {
				if (httpMessageConverter instanceof StringHttpMessageConverter) {
					((StringHttpMessageConverter) httpMessageConverter).setWriteAcceptCharset(false);
					((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
					break;
				}
			}
		}
		return restTemplate;
	}

	@SuppressWarnings("unchecked")
	public static <T> Map<String, T> postForObject(String url, String body) {
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
			HttpEntity<String> entity = new HttpEntity<>(body, headers);
			return RestUtils.getRestTemplate().postForObject(url, entity, Map.class);
		} catch (Exception e) {
			LogUtils.debug("地址" + url + "无法访问，请检查服务是否启动!!!");
			return null;
		}
	}
}
